package com.xhwl.data.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.common.dto.cent.sdata.BuildingDTO;
import com.xhwl.common.dto.cent.sdata.FloorDTO;
import com.xhwl.common.dto.cent.sdata.SpaceFunctionTypeDTO;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.config.IndustryEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.*;
import com.xhwl.common.query.cent.sdata.FloorQuery;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.common.query.cent.sdata.SpaceFunctionTypeQuery;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.data.service.IFloorService;
import com.xhwl.data.service.IOrganizationService;
import com.xhwl.data.service.IOrganizationTypeService;
import com.xhwl.data.service.ISpaceFunctionTypeService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 10:32 2021/1/23
 */
@RestController
public class FloorController {

    @Autowired
    private IFloorService floorService;

    @Autowired
    private IOrganizationService organizationService;

    @Autowired
    private ISpaceFunctionTypeService spaceFunctionTypeService;

    @Autowired
    private IOrganizationTypeService organizationTypeService;

    @RequestMapping(value = "/floor/insert", method = RequestMethod.POST)
    public ResultJson insert(@RequestBody FloorDTO floor, Account account) {
        if (StringUtils.isEmpty(floor.getName()) || floor.getName().length() > 32) {
            return ResultJson.fail("名称输入错误");
        }
        if (StringUtils.isNotEmpty(floor.getCode()) && floor.getCode().length() > 36) {
            return ResultJson.fail("编码输入错误");
        }
        if (null != floor.getId()) {
            return floorService.update(floor);
        } else {
            if (null == floor.getParentId() || floor.getParentId().toString().length() > 11) {
                return ResultJson.fail("上级信息错误");
            }
            return floorService.create(floor);
        }
    }

    @RequestMapping(value = "/floor/batch-insert")
    public ResultJson batchCreate(@RequestBody List<FloorDTO> floors) {
        if (CollectionUtils.isEmpty(floors)) {
            return ResultJson.success();
        }
        long count = floors.stream().map(FloorDTO::getCode).distinct().count();
        if(floors.size() > count){
            return ResultJson.fail("编码重复");
        }
        for (FloorDTO floor : floors) {
            if (StringUtils.isEmpty(floor.getName()) || floor.getName().length() > 32) {
                return ResultJson.fail("名称输入错误");
            }
            if (StringUtils.isNotEmpty(floor.getCode()) && floor.getCode().length() > 36) {
                return ResultJson.fail("编码输入错误");
            }
            if (null == floor.getParentId() || floor.getParentId().toString().length() > 11) {
                return ResultJson.fail("上级信息错误");
            }
        }
        return floorService.batchCreate(floors);
    }

    @RequestMapping(value = "/floor/delete")
    public ResultJson delete(Integer id, Account account) {
        return floorService.delete(id, account);
    }

    @RequestMapping(value = "/floor/page")
    public ResultJson page(@RequestBody FloorQuery query, Page page, Account account) {
        Page<Floor> page1 = floorService.page(query, account, page);
        return ResultJson.success(convertDTO(page1,query.getTypeId()));

    }

    @RequestMapping(value = "/floor/detail")
    public ResultJson detail(Integer id, Integer orgId,Integer typeId) {
        if (null == id && null == orgId) {
            return ResultJson.fail("参数错误");
        }
        FloorQuery floorQuery = new FloorQuery();
        floorQuery.withOrgId(orgId).withId(id);
        Floor floor = floorService.find(floorQuery);
        if (null == floor) {
            return ResultJson.success();
        }
        List<SpaceFunctionType> spaceFunctionTypes = listFunctionType();
        FloorDTO floorDTO = processBean(floor, spaceFunctionTypes,typeId);
        return ResultJson.success(floorDTO);
    }

    @RequestMapping(value = "/floor/count")
    public ResultJson count(Integer projectId) {
        if (null == projectId) {
            return ResultJson.fail("参数错误");
        }
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.eq("type", OrganizationTypeEnum.FLOOR.id);
        organizationQueryWrapper.eq("project_id", projectId);
        int count = organizationService.count(organizationQueryWrapper);
        return ResultJson.success(count);
    }

    /**
     * 获取当前编码
     *
     * @return
     */
    @GetMapping("/floor/get-current-code")
    public ResultJson getCurrentCode() {
        return ResultJson.success().setResult(floorService.getCurrentCode());
    }

    private Page convertDTO(Page page,Integer typeId) {
        if (page.getRecords().isEmpty()) {
            return page;
        }
        List<Floor> source = page.getRecords();
        List<FloorDTO> result = new ArrayList<>(source.size());
        List<SpaceFunctionType> spaceFunctionTypes = listFunctionType();
        for (Floor floor : source) {
            FloorDTO floorDTO = processBean(floor, spaceFunctionTypes,typeId);
            // 房间数
            OrganizationQuery query = new OrganizationQuery();
            query.withParentId(floor.getOrganizationId());
            query.withIndustryId(IndustryEnum.SCH.id);
            List<Organization> list = organizationService.list(query);
            floorDTO.setRoomNum(list.size());
            result.add(floorDTO);
        }
        return page.setRecords(result);
    }

    private FloorDTO processBean(Floor floor, List<SpaceFunctionType> spaceFunctionTypes,Integer typeId) {
        FloorDTO floorDTO = new FloorDTO();
        BeanUtils.copyProperties(floor, floorDTO);
        //填充功能名称
        if (null != floorDTO.getFunctionType()) {
            for (SpaceFunctionType spaceFunctionType : spaceFunctionTypes) {
                if (spaceFunctionType.getId().equals(floorDTO.getFunctionType())) {
                    floorDTO.setFunctionName(spaceFunctionType.getName());
                    break;
                }
            }
        }
        dealJson(floorDTO,typeId);
        return floorDTO;
    }

    private List<SpaceFunctionType> listFunctionType() {
        return spaceFunctionTypeService.list(new QueryWrapper<SpaceFunctionType>()
                .eq("org_type", OrganizationTypeEnum.FLOOR.getId()));
    }

    /**
     * 兼容历史数据
     */
    private void dealJson (Floor param,Integer typeId){
        if(typeId == null){
            return;
        }
        QueryWrapper<OrganizationType> organizationTypeQueryWrapper = new QueryWrapper<>();
        organizationTypeQueryWrapper.eq("id", typeId);
        OrganizationType organizationType = organizationTypeService.getOne(organizationTypeQueryWrapper);
        String source = organizationType.getSource();
        if(org.apache.commons.lang3.StringUtils.isEmpty(source)){
            return;
        }
        Map<String,Object> map = new HashMap<>();
        JSONObject sourceJson = JSON.parseObject(source);
        JSONArray fields = sourceJson.getJSONArray("fields");
        if(CollectionUtil.isNotEmpty(fields)) {
            for (int i = 0; i < fields.size(); i++) {
                JSONObject fieldJsonObject = fields.getJSONObject(i);
                fieldJsonObject.remove("__config__");
                String vModel = fieldJsonObject.getString("vModel");
                //兼容以前数据
                if ("name".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getName() != null ? param.getName() : "");
                    map.put("name",param.getName() != null ? param.getName() : "");
                } else if ("code".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getCode() != null ? param.getCode() : "");
                    map.put("code",param.getCode() != null ? param.getCode() : "");
                } else if ("sortField".equals(vModel)){
                    fields.getJSONObject(i).put("defaultValue",param.getSortField() != null ? param.getSortField() : "");
                    map.put("sortField",param.getSortField() != null ? param.getSortField() : "");
                } else {
                    if(param.getExpand() != null) {
                        JSONObject jsonObject = JSON.parseObject(param.getExpand());
                        if(jsonObject.get(vModel) != null) {
                            fields.getJSONObject(i).put("defaultValue", jsonObject.get(vModel));
                            map.put(vModel,jsonObject.get(vModel));
                        }else{
                            map.put(vModel,"");
                        }
                    }else{
                        map.put(vModel,"");
                    }
                }
            }
        }
        param.setExpand(JSON.toJSONString(sourceJson));
        param.setFullData(JSON.toJSONString(map));
    }
}
